<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="clearSearch">
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('租户名称')" prop="adminName">
          <el-input v-model="page.adminName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('租户账号')" prop="accountNumber">
          <el-input v-model="page.accountNumber"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('创建时间')" prop="timeValue">
          <el-date-picker
              v-model="page.timeValue"
              style="width: 100%"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <el-row :gutter="24">
        <el-col :span="24" style="text-align: right">
          <el-button v-show="$permiss[33]" type="primary" @click="addTenant">{{ $t('添加租户') }}</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <Table :tableData="tableData" :tableColumn="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
               @handleCurrentChange="handleCurrentChange">
          <template slot-scope="{row}" slot="status">
            <el-switch :disabled="!$permiss[36]" @change="changeStatus(row)"
                       :value="row.status"></el-switch>
          </template>
          <template slot-scope="{row}" slot="handle">
            <el-button v-show="$permiss[35]" type="text" @click="editTenant(row)">{{ $t('编辑') }}</el-button>
            <el-button type="text" @click="tenantRecharge(row)" v-show="$permiss[37]">{{ $t('充值') }}</el-button>
            <el-button v-show="$permiss[515]" type="text" @click="resetPassword(row)">{{
                $t('重置密码')
              }}
            </el-button>
          </template>
        </Table>
      </el-row>
    </el-card>
    <Dialog @confirm="visibleConfirm" @cancel="visible.isShow = false" :visible.sync="visible.isShow"
            :title="visible.title" @close="clearForm()">
      <el-form ref="form" :model="form" label-width="80px" :rules="rulesForm">
        <el-form-item :label="$t('租户名称')" prop="adminName">
          <el-input v-model="form.adminName"></el-input>
        </el-form-item>
        <el-form-item v-if="visible.type !== 'edit'" :label="$t('租户账号')" prop="accountNumber">
          <el-input v-model="form.accountNumber"></el-input>
        </el-form-item>
        <!--        <el-form-item :label="$t('tenant.tenantPassword')" prop="password">-->
        <!--          <el-input v-model="form.password"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item v-if="visible.type !== 'edit'" :label="$t('状态')" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">{{ $t('启用') }}</el-radio>
            <el-radio :label="0">{{ $t('禁用') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--     充值-->
    <Dialog :visible.sync="rechargeVisible" @cancel="rechargeVisible = false" :title="$t('账户充值')"
            @close="clearRechargeForm" @confirm="rechargeConfirm">
      <el-form label-width="120px" :model="rechargeForm" ref="rechargeForm">
        <el-form-item :label="$t('充值方式')" prop="topUpType" :rules="[
               {required: true, message: this.$t('请选择充值方式'), trigger: 'change'}
        ]">
          <el-select v-model="rechargeForm.topUpType" style="width: 100%;">
            <el-option v-for="item in rechargeMode" :value="item.value" :label="item.label"
                       :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('收款银行名称')" prop="bankName" :rules="[
               {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ]">
          <el-input v-model="rechargeForm.bankName"/>
        </el-form-item>
        <el-form-item :label="$t('银行账户')" prop="bankAccount" :rules="[
               {required: true, message: this.$t('不能为空'), trigger: 'blur'},
        ]">
          <el-input v-model="rechargeForm.bankAccount" oninput="value = value.replace(/[^\d]/g, '')"/>
        </el-form-item>
        <el-form-item :label="$t('充值金额')" prop="topUpAmount" :rules="[
               {required: true, message: this.$t('不能为空'), trigger: 'blur'},
                 {validator:validatorAmount}
        ]">
          <el-input v-model="rechargeForm.topUpAmount" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item :label="$t('赠送金额')" prop="giveAmount" :rules="[
            {validator:validatorAmount}
        ]">
          <el-input v-model="rechargeForm.giveAmount" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item :label="$t('交易流水')" prop="giveAmount">
          <el-input v-model="rechargeForm.dealFlow" oninput="value = value.replace(/[^\d]/g, '')"/>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remark">
          <el-input type="textarea" :rows="4" v-model="rechargeForm.remark"/>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {deepClone} from "@/utils/tools";
import qs from 'qs'
import {fetchTenantList, addTenantUser, editSystemUser, updateStatusSystemUser,resetPassword,tenantRecharge} from "@/api/system";
import {dateFormatSection} from '@/utils/tools'
export default {
  name: 'tenantList',
  data() {
    const validatePass = (rule, value, callback) => {
      const RegExp = /^[0-9a-zA-Z]*$/g
      if (!RegExp.test(value)) {
        callback(new Error(this.$t('非法字符')))
      }
      callback()
    }
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      form: {
        status: 1
      },
      visible: {
        isShow: false,
        title: '',
        type: ''
      },
      timeValue: null,
      tableData: [],
      rulesForm: {
        adminName: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'},
        ],
        accountNumber: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'},
          {min: 6, max: 15, message: this.$t('账号长度为6-15位'), trigger: 'blur'},
        ],
      },
      tableColumn: [
        {label: this.$t('租户名称'), prop: 'adminName', align: 'center'},
        {label: this.$t('租户账号'), prop: 'accountNumber', align: 'center'},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center'},
        {label: this.$t('创建人'), prop: 'inputName', align: 'center'},
        {label: this.$t('创建时间'), prop: 'creationTime', align: 'center', width: 150},
        {label: this.$t('所属角色'), prop: 'name', align: 'center'},
        {label: this.$t('状态'), slot: 'status', align: 'center'},
        {
          label: this.$t('操作'),
          slot: 'handle',
          align: 'center',
          width: 200,
          isHide: !this.$permiss[37] && !this.$permiss[35] && !this.$permiss[515]
        },
      ],
      rechargeVisible: false,
      rechargeForm: {},
      rechargeMode: [
        {label: this.$t('微信'), value: 1},
        {label: this.$t('支付宝'), value: 2},
        {label: this.$t('银行卡汇款'), value: 3},
      ],
      tableRows: {}
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const timeValue = dateFormatSection(this.page.timeValue)
      const params = Object.assign({}, this.page, {
        datetimeStart: timeValue && timeValue.length ? timeValue[0] : undefined,
        datetimeEnd: timeValue && timeValue.length ? timeValue[1] : undefined,
      })
      delete params.timeValue
      const res = await fetchTenantList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.status = item.status === 1
          return item
        })
        this.page = Object.assign({}, this.page, {
          total: total
        })
      }
    },
    validatorAmount(rules, value, callBack) {
      const val = parseFloat(value)
      if (val === 0) {
        callBack(new Error(this.$t('不能为零')));
      }
      callBack()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    dataChange(value) {
      if (value) {
        this.page = Object.assign({}, this.page, {
          datetimeStart: value[0],
          datetimeEnd: value[1]
        })
      } else {
        this.page = Object.assign({}, this.page, {
          datetimeStart: '',
          datetimeEnd: ''
        })
      }
    },
    editTenant(row) {
      this.form = {
        adminName: row.adminName,
        phone: row.phone,
        adminUserId: row.adminUserId,
        accountNumber: row.accountNumber
      }
      this.visible = {
        isShow: true,
        type: 'edit',
        title: this.$t('编辑租户')
      }
    },
    addTenant() {
      this.visible = {
        isShow: true,
        type: 'add',
        title: this.$t('新增租户')
      }
    },
    visibleConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          const api = (params) => this.visible.type === 'add' ? addTenantUser(params) : editSystemUser(params)
          const res = await api({...this.form})
          if (res.code === 1) {
            this.$message.success(this.$t('修改成功'))
            this.clearForm()
            this.visible.isShow = false
            this.getTableData()
          }
        }
      })
    },
    // 租户充值
    tenantRecharge(row) {
      this.tableRows = deepClone(row)
      this.rechargeVisible = true
    },
    // 重置密码
    async resetPassword(row) {
      this.$confirm(this.$t('确定重置密码?'), this.$t('提示'),).then(async () => {
        const params = {
          adminUserId: row.adminUserId,
        }
        const res = await resetPassword(params)
        if (res.code === 1) {
          this.$message.success(this.$t('重置成功'))
          this.getTableData()
        }
      });
    },
    // 充值提交
    async rechargeConfirm() {
      this.$refs.rechargeForm.validate(async v => {
        if (v) {
          const {adminName, adminUserId} = this.tableRows
          const params = Object.assign({}, this.rechargeForm, {
            topUpAmount: parseFloat(this.rechargeForm.topUpAmount),
            giveAmount: parseFloat(this.rechargeForm.giveAmount),
          })
          const res = await tenantRecharge({...params, adminName, adminUserId})
          if (res.code === 1) {
            this.$message.success(this.$t('新增成功'))
            this.clearRechargeForm()
            this.rechargeVisible = false
          }
        }
      })
    },
    // 清空充值表单
    clearRechargeForm() {
      this.rechargeForm = {}
      this.$refs.rechargeForm.resetFields()
    },
    clearForm() {
      this.form = {
        status: 1
      }
      this.$refs.form.resetFields()
    },
    async changeStatus(row) {
      this.$confirm(this.$t('请慎重考虑是否进行该操作'), this.$t('提示'),).then(async () => {
        const params = {
          adminUserId: row.adminUserId,
          status: row.status ? 0 : 1
        }
        const res = await updateStatusSystemUser(qs.stringify(params))
        if (res.code === 1) {
          this.$message.success(this.$t('修改成功'))
          this.getTableData()
        }
      });

    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },
  }
}
</script>

<style scoped>

</style>
